﻿//using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Results;
using WebApplication1.Auth.common;

namespace WebApplication1.Outside.v1
{
    /// <summary>
    /// Authenticate服务
    /// </summary>
    [RoutePrefix("outside/zplus")]
    /// <summary>
    /// 授权服务
    /// </summary>
    public class AuthenticateController : ApiController
    {
        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Authenticate/GetToken")]
        [AllowAnonymous]
        public IHttpActionResult GetToken([FromBody]UserModel userinfo)
        {
            var loginsuccess = Login(userinfo);//登录验证
            var tokenString = "";
            if (!loginsuccess) return Unauthorized();//登录失败

            if (loginsuccess)//登录验证成功
            {
                Dictionary<string, object> payLoad = new Dictionary<string, object>();
                payLoad.Add("sub", "rober");
                payLoad.Add("jti", "09e572c7-62d0-4198-9cce-0915d7493806");
                payLoad.Add("nbf", null);
                payLoad.Add("exp", null);
                payLoad.Add("iss", "roberIssuer");
                payLoad.Add("aud", "roberAudience");
                payLoad.Add("age", 30);

                tokenString = TokenContext.CreateToken(payLoad, 30);
            }

            return Json<object>(new
            {
                access_token = tokenString,
                token_type = "Bearer"
            });
        }

        /// <summary>
        /// 授权验证测试
        /// </summary>
        /// <returns></returns>
        
        [HttpGet]
        [Route("Authenticate/test")]
        public string test()
        {
            return "test";
        }

        /// <summary>
        /// 测试方法
        /// </summary>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        [HttpPost]
        public bool Login(UserModel userinfo)
        {
            if (userinfo.username == "randy" && userinfo.password == "123456")
            {
                return true;
            }
            return false;
        }
    }

    /// <summary>
    /// 测试model
    /// </summary>
    public class UserModel
    {
        public string username { get; set; }
        public string password { get; set; }
    }
}
